package cn.cdeden.knowledge.service.impl;

import cn.cdeden.common.core.utils.MapstructUtils;
import cn.cdeden.common.core.utils.StringUtils;
import cn.cdeden.common.core.utils.page.TableDataInfo;
import cn.cdeden.common.mybatis.validator.QueryHelpMybatisPlus;
import cn.cdeden.common.satoken.utils.LoginHelper;
import cn.cdeden.knowledge.domain.EnterpriseFilesTree;
import cn.cdeden.knowledge.domain.EnterprisePerm;
import cn.cdeden.knowledge.domain.dto.*;
import cn.cdeden.knowledge.domain.vo.EnterpriseMemberVo;
import cn.cdeden.knowledge.domain.vo.EnterprisePermVo;
import cn.cdeden.knowledge.enums.PermTypeEnum;
import cn.cdeden.knowledge.mapper.EnterpriseFilesTreeMapper;
import cn.cdeden.knowledge.mapper.EnterprisePermMapper;
import cn.cdeden.knowledge.service.EnterprisePermService;
import cn.cdeden.knowledge.utils.PageUtil;
import cn.cdeden.system.api.RemoteDeptService;
import cn.cdeden.system.api.RemotePostService;
import cn.cdeden.system.api.RemoteRoleService;
import cn.cdeden.system.api.RemoteUserService;
import cn.cdeden.system.api.domain.enums.EnterprisePermTypeEnum;
import cn.cdeden.system.api.domain.enums.FileTypeEnum;
import cn.cdeden.system.api.domain.vo.*;
import cn.cdeden.system.api.model.LoginUser;
import cn.cdeden.system.api.model.RoleDTO;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;


@Service
@RequiredArgsConstructor
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class EnterprisePermServiceImpl extends ServiceImpl<EnterprisePermMapper, EnterprisePerm> implements EnterprisePermService {

    @DubboReference(check = false)
    private final RemoteRoleService sysRoleService;

    @DubboReference(check = false)
    private final RemoteUserService sysUserService;

    @DubboReference(check = false)
    private final RemoteDeptService sysDeptService;

    @DubboReference(check = false)
    private final RemotePostService remotePostService;

    private final EnterprisePermMapper enterprisePermMapper;

    private final EnterpriseFilesTreeMapper enterpriseFilesTreeMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(EnterprisePermDto resources) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        EnterprisePerm entity = MapstructUtils.convert(resources, EnterprisePerm.class);
        entity.setId(null);
        entity.setCreateId(loginUser.getUserId().toString());
        entity.setCreateTime(new Date());
        entity.setCreateBy(loginUser.getUsername());
        return enterprisePermMapper.insert(entity);
    }


    /**
     * 权限继承：paretId与newTreeId是在文件夹中是父子级关系(新)
     * @param parentId
     * @param newTreeId
     * @return
     */
    @Override
    public Boolean extendPerm(Long parentId, Long newTreeId){
        if (parentId.longValue() == newTreeId.longValue())return false;
        EnterpriseFilesTree enterpriseFilesTree = enterpriseFilesTreeMapper.selectById(newTreeId);
        if (enterpriseFilesTree == null) return false;
        //继承水印
        EnterpriseFilesTree parent = enterpriseFilesTreeMapper.selectById(parentId);
        enterpriseFilesTree.setWaterMarkId(parent.getWaterMarkId());
        enterpriseFilesTreeMapper.updateById(enterpriseFilesTree);

        //继承权限
        List<EnterprisePerm> list = enterprisePermMapper.lambdaQuery().eq(EnterprisePerm::getTreeNodeId, parentId).list();

        //查询是否已有权限
        List<EnterprisePerm> exist = enterprisePermMapper.lambdaQuery().eq(EnterprisePerm::getTreeNodeId, newTreeId).list();

        if(exist.size() > 0) {
            return false;
        }else {
            for (EnterprisePerm enterprisePerm : list) {
                Integer query = enterprisePerm.getQuery();
                Integer manage = enterprisePerm.getManage();
                Integer editor = enterprisePerm.getEditor();
                String params = enterprisePerm.getParams();
                Long typeId = enterprisePerm.getTypeId();
                Integer type = enterprisePerm.getType();
                EnterprisePermDto extendPerm = new EnterprisePermDto();
                extendPerm.setIsExtend(1).setParentTreeNodeId(parentId).setTreeNodeId(newTreeId).setQuery(query).setManage(manage).setEditor(editor).setType(type).setTypeId(typeId).setParams(params);
                insert(extendPerm);
            }
            return true;
        }

    }

    @Override
    public List<EnterprisePerm> getPerms(Long parentTreeNodeId, Long userId, EnterprisePermTypeEnum enterprisePermTypeEnum) {
        //角色
        List<RemoteRoleVo> remoteRoleVos = sysRoleService.selectUserRoleByUserId(userId);
        List<Long> roleIds = remoteRoleVos.stream().map(RemoteRoleVo::getRoleId).collect(Collectors.toList());
        //部门
        RemoteUserVo remoteUserVo = sysUserService.selectUserByUserId(userId);
        Long deptId = remoteUserVo.getDeptId();
        List<RemoteDeptVo> superiorAll = sysDeptService.getSuperiorAll(deptId);
        List<Long> deptIds = superiorAll.stream().map(RemoteDeptVo::getDeptId).collect(Collectors.toList());
        //岗位
        List<Long> jobIds = remotePostService.getAllJobById(userId);
//        List<Long> jobIds = allJobById.stream().map(RemotePostVo::getJobId).collect(Collectors.toList());
////        FileUserDto user = null;
//        LoginUser user = null;
//        if (userId == null){
////            user = FileUserUtils.getUser();
//            LoginUser loginUser = LoginHelper.getLoginUser();
//        }else {
////            user  = FileUserUtils.getUserInfo(String.valueOf(userId));
//            user = LoginHelper.getLoginUserByUserId(userId);
//        }

//        List<Long> roleIds = user.getRoles().stream().map(RoleSmallDto::getId).collect(Collectors.toList());
//        List<Long> jobIds=user.getJobs().stream().map(JobSmallDto::getId).collect(Collectors.toList());
//        Long deptId = user.getDeptId();


//        List<DeptDto> superiorAll = sysDeptService.getSuperiorAll(deptId.toString());
        //用户自身部门以及上级部门
//        List<Long> deptIds = superiorAll.stream().map(DeptDto::getId).collect(Collectors.toList());


        List<String> list = new ArrayList<>();
        if (enterprisePermTypeEnum.equals(EnterprisePermTypeEnum.QUERY)){
            list.add(EnterprisePermTypeEnum.QUERY.getPermTypeCode());
            list.add(EnterprisePermTypeEnum.PRINT.getPermTypeCode());
            list.add(EnterprisePermTypeEnum.DOWNLOAD.getPermTypeCode());
            list.add(EnterprisePermTypeEnum.EDITOR.getPermTypeCode());
            list.add(EnterprisePermTypeEnum.UPLOAD.getPermTypeCode());
            list.add(EnterprisePermTypeEnum.MANAGE.getPermTypeCode());
        }else if(enterprisePermTypeEnum.equals(EnterprisePermTypeEnum.PRINT)){
            list.add(EnterprisePermTypeEnum.PRINT.getPermTypeCode());
            list.add(EnterprisePermTypeEnum.DOWNLOAD.getPermTypeCode());
            list.add(EnterprisePermTypeEnum.EDITOR.getPermTypeCode());
            list.add(EnterprisePermTypeEnum.UPLOAD.getPermTypeCode());
            list.add(EnterprisePermTypeEnum.MANAGE.getPermTypeCode());
        } else if (enterprisePermTypeEnum.equals(EnterprisePermTypeEnum.DOWNLOAD)) {
            list.add(EnterprisePermTypeEnum.DOWNLOAD.getPermTypeCode());
            list.add(EnterprisePermTypeEnum.EDITOR.getPermTypeCode());
            list.add(EnterprisePermTypeEnum.UPLOAD.getPermTypeCode());
            list.add(EnterprisePermTypeEnum.MANAGE.getPermTypeCode());
        } else if (enterprisePermTypeEnum.equals(EnterprisePermTypeEnum.EDITOR)){
            list.add(EnterprisePermTypeEnum.EDITOR.getPermTypeCode());
            list.add(EnterprisePermTypeEnum.UPLOAD.getPermTypeCode());
            list.add(EnterprisePermTypeEnum.MANAGE.getPermTypeCode());
        } else if (enterprisePermTypeEnum.equals(EnterprisePermTypeEnum.UPLOAD)){
            list.add(EnterprisePermTypeEnum.UPLOAD.getPermTypeCode());
            list.add(EnterprisePermTypeEnum.MANAGE.getPermTypeCode());
        }
        else if (enterprisePermTypeEnum.equals(EnterprisePermTypeEnum.MANAGE)){
            list.add(EnterprisePermTypeEnum.MANAGE.getPermTypeCode());
        }
        ArrayList<EnterprisePerm> enterprisePerms = new ArrayList<>();


        List<EnterprisePerm> userPerms = enterprisePermMapper.selectList(new LambdaQueryWrapper<EnterprisePerm>().eq(parentTreeNodeId != null, EnterprisePerm::getParentTreeNodeId, parentTreeNodeId)
            .eq(EnterprisePerm::getType, PermTypeEnum.USER.getPermTypeCode())
            .eq(EnterprisePerm::getTypeId, userId)
            .in(EnterprisePerm::getParams, list));
        enterprisePerms.addAll(userPerms);
        if (deptIds.size() > 0) {
            List<EnterprisePerm> deptPerms = enterprisePermMapper.selectList(new LambdaQueryWrapper<EnterprisePerm>().eq(parentTreeNodeId != null, EnterprisePerm::getParentTreeNodeId, parentTreeNodeId)
                .eq(EnterprisePerm::getType, PermTypeEnum.DEPT.getPermTypeCode())
                .in(EnterprisePerm::getTypeId, deptIds)
                .in(EnterprisePerm::getParams, list));
            enterprisePerms.addAll(deptPerms);
        }
        if (roleIds.size()>0) {
            List<EnterprisePerm> rolePerms = enterprisePermMapper.selectList(new LambdaQueryWrapper<EnterprisePerm>().eq(parentTreeNodeId != null, EnterprisePerm::getParentTreeNodeId, parentTreeNodeId)
                .eq(EnterprisePerm::getType, PermTypeEnum.ROLE.getPermTypeCode())
                .in(EnterprisePerm::getTypeId, roleIds)
                .in(EnterprisePerm::getParams, list));
            enterprisePerms.addAll(rolePerms);
        }
        if (jobIds.size()>0) {
            List<EnterprisePerm> jobPerms = enterprisePermMapper.selectList(new LambdaQueryWrapper<EnterprisePerm>().eq(parentTreeNodeId != null, EnterprisePerm::getParentTreeNodeId, parentTreeNodeId)
                .eq(EnterprisePerm::getType, PermTypeEnum.JOB.getPermTypeCode())
                .in(EnterprisePerm::getTypeId, jobIds)
                .in(EnterprisePerm::getParams, list));
            enterprisePerms.addAll(jobPerms);
        }
        enterprisePerms.stream().distinct();
        return enterprisePerms;
//        List<EnterprisePerm> userPerms = enterprisePermMapper.lambdaQuery().eq(parentTreeNodeId != null,EnterprisePerm::getParentTreeNodeId,parentTreeNodeId)
//            .eq(EnterprisePerm::getType,PermTypeEnum.USER.getPermTypeCode())
//            .eq(EnterprisePerm::getTypeId, user.getId())
//            .in(EnterprisePerm::getParams, list).list();
//        enterprisePerms.addAll(userPerms);
//        if (deptIds.size() > 0) {
//            List<EnterprisePerm> deptPerms = enterprisePermMapper.lambdaQuery().eq(parentTreeNodeId != null, EnterprisePerm::getParentTreeNodeId, parentTreeNodeId)
//                .eq(EnterprisePerm::getType, PermTypeEnum.DEPT.getPermTypeCode())
//                .in(EnterprisePerm::getTypeId, deptIds)
//                .in(EnterprisePerm::getParams, list).list();
//            enterprisePerms.addAll(deptPerms);
//        }
//        if (roleIds.size()>0) {
//            List<EnterprisePerm> rolePerms = enterprisePermMapper.lambdaQuery().eq(parentTreeNodeId != null, EnterprisePerm::getParentTreeNodeId, parentTreeNodeId)
//                .eq(EnterprisePerm::getType, PermTypeEnum.ROLE.getPermTypeCode())
//                .in(EnterprisePerm::getTypeId, roleIds)
//                .in(EnterprisePerm::getParams, list).list();
//            enterprisePerms.addAll(rolePerms);
//        }
//        if (jobIds.size()>0) {
//            List<EnterprisePerm> jobPerms = enterprisePermMapper.lambdaQuery().eq(parentTreeNodeId != null, EnterprisePerm::getParentTreeNodeId, parentTreeNodeId)
//                .eq(EnterprisePerm::getType, PermTypeEnum.JOB.getPermTypeCode())
//                .in(EnterprisePerm::getTypeId, jobIds)
//                .in(EnterprisePerm::getParams, list).list();
//
//            enterprisePerms.addAll(jobPerms);
//        }
//        enterprisePerms.stream().distinct();
//        return enterprisePerms;
//        return null;
    }

    @Override
    public List<Long> getPerms(EnterprisePermQueryParam enterprisePermQueryParam, Long userId, EnterprisePermTypeEnum enterprisePermTypeEnum) {
        List<String> list = new ArrayList<>();
        if (enterprisePermTypeEnum.equals(EnterprisePermTypeEnum.QUERY)){
            list.add(EnterprisePermTypeEnum.QUERY.getPermTypeCode());
            list.add(EnterprisePermTypeEnum.PRINT.getPermTypeCode());
            list.add(EnterprisePermTypeEnum.DOWNLOAD.getPermTypeCode());
            list.add(EnterprisePermTypeEnum.EDITOR.getPermTypeCode());
            list.add(EnterprisePermTypeEnum.UPLOAD.getPermTypeCode());
            list.add(EnterprisePermTypeEnum.MANAGE.getPermTypeCode());
        }else if(enterprisePermTypeEnum.equals(EnterprisePermTypeEnum.PRINT)){
            list.add(EnterprisePermTypeEnum.PRINT.getPermTypeCode());
            list.add(EnterprisePermTypeEnum.DOWNLOAD.getPermTypeCode());
            list.add(EnterprisePermTypeEnum.EDITOR.getPermTypeCode());
            list.add(EnterprisePermTypeEnum.UPLOAD.getPermTypeCode());
            list.add(EnterprisePermTypeEnum.MANAGE.getPermTypeCode());
        } else if (enterprisePermTypeEnum.equals(EnterprisePermTypeEnum.DOWNLOAD)) {
            list.add(EnterprisePermTypeEnum.DOWNLOAD.getPermTypeCode());
            list.add(EnterprisePermTypeEnum.EDITOR.getPermTypeCode());
            list.add(EnterprisePermTypeEnum.UPLOAD.getPermTypeCode());
            list.add(EnterprisePermTypeEnum.MANAGE.getPermTypeCode());
        } else if (enterprisePermTypeEnum.equals(EnterprisePermTypeEnum.EDITOR)){
            list.add(EnterprisePermTypeEnum.EDITOR.getPermTypeCode());
            list.add(EnterprisePermTypeEnum.UPLOAD.getPermTypeCode());
            list.add(EnterprisePermTypeEnum.MANAGE.getPermTypeCode());
        } else if (enterprisePermTypeEnum.equals(EnterprisePermTypeEnum.UPLOAD)){
            list.add(EnterprisePermTypeEnum.UPLOAD.getPermTypeCode());
            list.add(EnterprisePermTypeEnum.MANAGE.getPermTypeCode());
        }
        else if (enterprisePermTypeEnum.equals(EnterprisePermTypeEnum.MANAGE)){
            list.add(EnterprisePermTypeEnum.MANAGE.getPermTypeCode());
        }
        enterprisePermQueryParam.setParams(list);
        QueryWrapper<EnterprisePerm> predicate = QueryHelpMybatisPlus.getPredicate(enterprisePermQueryParam);
        LoginUser user = null;
        if (userId == null){
            user = LoginHelper.getLoginUser();
        }else {
            user  = sysUserService.getUserInfo(userId);
        }

        List<Long> roleIds = user.getRoles().stream().map(RoleDTO::getRoleId).collect(Collectors.toList());

//        List<Long> jobIds=user.getJobs().stream().map(JobSmallDto::getId).collect(Collectors.toList());
        Long deptId = user.getDeptId();


        List<RemoteDeptVo> superiorAll = sysDeptService.getSuperiorAll(deptId);
        //用户自身部门以及上级部门
        List<Long> deptIds = superiorAll.stream().map(RemoteDeptVo::getDeptId).collect(Collectors.toList());

        predicate.lambda().and(consumer-> {
            consumer.and(consumer1 -> {
                consumer1.eq(EnterprisePerm::getType, PermTypeEnum.USER.getPermTypeCode()).eq(EnterprisePerm::getTypeId, userId);
            }).or(deptIds != null && deptIds.size() > 0, action -> {
                action.eq(deptIds != null && deptIds.size() > 0, EnterprisePerm::getType, PermTypeEnum.DEPT.getPermTypeCode()).in(EnterprisePerm::getTypeId, deptIds);
            }).or(roleIds != null && roleIds.size() > 0, action -> {
                action.eq(roleIds != null && roleIds.size() > 0, EnterprisePerm::getType, PermTypeEnum.ROLE.getPermTypeCode()).in(EnterprisePerm::getTypeId, roleIds);
            });
//                .or(jobIds != null && jobIds.size() > 0, action -> {
//                action.eq(jobIds != null && jobIds.size() > 0, EnterprisePerm::getType, PermTypeEnum.JOB.getPermTypeCode()).in(EnterprisePerm::getTypeId, jobIds);
//            });
        });
        List<EnterprisePerm> enterprisePerms = enterprisePermMapper.selectList(predicate);
        List<Long> collect = enterprisePerms.stream().map(EnterprisePerm::getTreeNodeId).distinct().collect(Collectors.toList());
        return collect;
    }

    /**
     * 检查是否有对应权限权限
     */
    @Override
    public Boolean checkPermission(Long treeNodeId, EnterprisePermTypeEnum enterprisePermTypeEnum,Long userId) {

        String perms = getPerms(treeNodeId, userId);
        if (perms == null){
            return false;
        }
        if (perms.equals(EnterprisePermTypeEnum.QUERY.getPermTypeCode())) {
            return enterprisePermTypeEnum == EnterprisePermTypeEnum.QUERY;
        } else if (perms.equals(EnterprisePermTypeEnum.PRINT.getPermTypeCode())) {
            return enterprisePermTypeEnum == EnterprisePermTypeEnum.PRINT || enterprisePermTypeEnum == EnterprisePermTypeEnum.QUERY;
        } else if (perms.equals(EnterprisePermTypeEnum.DOWNLOAD.getPermTypeCode())) {
            return enterprisePermTypeEnum == EnterprisePermTypeEnum.PRINT || enterprisePermTypeEnum == EnterprisePermTypeEnum.QUERY || enterprisePermTypeEnum == EnterprisePermTypeEnum.DOWNLOAD;
        } else if (perms.equals(EnterprisePermTypeEnum.EDITOR.getPermTypeCode())) {
            return enterprisePermTypeEnum == EnterprisePermTypeEnum.PRINT || enterprisePermTypeEnum == EnterprisePermTypeEnum.QUERY || enterprisePermTypeEnum == EnterprisePermTypeEnum.DOWNLOAD || enterprisePermTypeEnum == EnterprisePermTypeEnum.EDITOR;
        } else if (perms.equals(EnterprisePermTypeEnum.UPLOAD.getPermTypeCode())) {
            return enterprisePermTypeEnum == EnterprisePermTypeEnum.PRINT || enterprisePermTypeEnum == EnterprisePermTypeEnum.QUERY || enterprisePermTypeEnum == EnterprisePermTypeEnum.DOWNLOAD || enterprisePermTypeEnum==EnterprisePermTypeEnum.EDITOR || enterprisePermTypeEnum == EnterprisePermTypeEnum.UPLOAD;
        } else if (perms.equals(EnterprisePermTypeEnum.MANAGE.getPermTypeCode())) {
            return enterprisePermTypeEnum == EnterprisePermTypeEnum.PRINT || enterprisePermTypeEnum == EnterprisePermTypeEnum.QUERY || enterprisePermTypeEnum == EnterprisePermTypeEnum.DOWNLOAD || enterprisePermTypeEnum==EnterprisePermTypeEnum.EDITOR || enterprisePermTypeEnum == EnterprisePermTypeEnum.UPLOAD || enterprisePermTypeEnum == EnterprisePermTypeEnum.MANAGE;
        } else {
            return false;
        }
    }


    @Override
    public String getPerms(Long treeNodeId, Long userId) {
        LoginUser user = null;
        if (userId == null){
            user = LoginHelper.getLoginUser();
        }else {
            user  = sysUserService.getUserInfo(userId);
        }
        userId = user.getUserId();
        boolean superAdmin = LoginHelper.isSuperAdmin(userId);
        if (superAdmin) return EnterprisePermTypeEnum.MANAGE.getPermTypeCode();
        boolean a = isCreator(userId, treeNodeId);
        if (a) return EnterprisePermTypeEnum.MANAGE.getPermTypeCode();

        //角色
        List<RemoteRoleVo> remoteRoleVos = sysRoleService.selectUserRoleByUserId(userId);
        List<Long> roleIds = remoteRoleVos.stream().map(RemoteRoleVo::getRoleId).collect(Collectors.toList());


        //岗位
//        List<RemotePostVo> allJobById = MapstructUtils.convert(sysJobService.getAllJobById(userId), RemotePostVo.class);
//        List<Long> jobIds = allJobById.stream().map(RemotePostVo::getJobId).collect(Collectors.toList());
        List<Long> jobIds = remotePostService.getAllJobById(userId);


        //部门
        RemoteUserVo remoteUserVo = sysUserService.selectUserByUserId(userId);
        Long deptId = remoteUserVo.getDeptId();
        List<RemoteDeptVo> superiorAll = sysDeptService.getSuperiorAll(deptId);
        List<Long> deptIds = superiorAll.stream().map(RemoteDeptVo::getDeptId).collect(Collectors.toList());
//        FileUserDto user = null;
//        if (userId == null){
//            user = FileUserUtils.getUser();
//        }else {
//            user  = FileUserUtils.getUserInfo(String.valueOf(userId));
//        }
//        userId = user.getId();
//        //检验是否为admin
//        boolean b = isAdmin(userId);
//        if (b) return EnterprisePermTypeEnum.MANAGE.getPermTypeCode();
//
//        boolean a = isCreator(userId, treeNodeId);
//        if (a) return EnterprisePermTypeEnum.MANAGE.getPermTypeCode();
//
//        List<Long> roleIds = user.getRoles().stream().map(RoleSmallDto::getId).collect(Collectors.toList());
//        List<Long> jobIds=user.getJobs().stream().map(JobSmallDto::getId).collect(Collectors.toList());
//        Long deptId = user.getDeptId();
//
//
//        List<DeptDto> superiorAll = sysDeptService.getSuperiorAll(deptId.toString());
//        //用户自身部门以及上级部门
//        List<Long> deptIds = superiorAll.stream().map(DeptDto::getId).collect(Collectors.toList());

        //顶级权限
        EnterprisePerm topPerm = null;



        //部门顶级权限
        EnterprisePerm deptPerm = null;

        //角色权限
        EnterprisePerm rolePerm = null;
        if (isAdmin(null)){
            return EnterprisePermTypeEnum.MANAGE.getPermTypeCode();
        }else {
            if (treeNodeId==1){
//                if (isEnterpriseAdmin(null))return EnterprisePermTypeEnum.MANAGE.getPermTypeCode();
//                else {
                    if (isCreator(userId, treeNodeId))return EnterprisePermTypeEnum.MANAGE.getPermTypeCode();
                    else {
                        PriorityQueue<EnterprisePerm> enterprisePerms = new PriorityQueue<>();
                        PriorityQueue<EnterprisePerm> enterpriseDeptPerms = new PriorityQueue<>();
                        PriorityQueue<EnterprisePerm> enterpriseRolePerms = new PriorityQueue<>();
                        //获取当前用户权限
                        EnterprisePerm userPerm = enterprisePermMapper.selectOne(new LambdaQueryWrapper<EnterprisePerm>().eq(EnterprisePerm::getType, PermTypeEnum.USER.getPermTypeCode())
                            .eq(EnterprisePerm::getTreeNodeId, treeNodeId)
                            .eq(EnterprisePerm::getTypeId, userId));
                        //获取当前用户部门权限
                        List<EnterprisePerm> deptPerms = enterprisePermMapper.selectList(new LambdaQueryWrapper<EnterprisePerm>().eq(EnterprisePerm::getType, PermTypeEnum.DEPT.getPermTypeCode())
                            .eq(EnterprisePerm::getTreeNodeId, treeNodeId)
                            .in(CollectionUtils.isNotEmpty(deptIds), EnterprisePerm::getTypeId, deptIds));
                        //获取当前用户角色权限
                        List<EnterprisePerm> rolePerms = enterprisePermMapper.selectList(new LambdaQueryWrapper<EnterprisePerm>().eq(EnterprisePerm::getType, PermTypeEnum.ROLE.getPermTypeCode())
                            .eq(EnterprisePerm::getTreeNodeId, treeNodeId)
                            .in(roleIds != null && roleIds.size() > 0, EnterprisePerm::getTypeId, roleIds));
                        //获取当前职位职位权限
                        EnterprisePerm jobPerm = enterprisePermMapper.selectOne(new LambdaQueryWrapper<EnterprisePerm>().eq(EnterprisePerm::getType, PermTypeEnum.JOB.getPermTypeCode())
                            .eq(EnterprisePerm::getTreeNodeId, treeNodeId)
                            .in(jobIds != null && jobIds.size() > 0, EnterprisePerm::getTypeId, jobIds));


//                        //获取当前用户权限
//                        EnterprisePerm userPerm = enterprisePermMapper.lambdaQuery().eq(EnterprisePerm::getType, PermTypeEnum.USER.getPermTypeCode())
//                            .eq(EnterprisePerm::getTreeNodeId, treeNodeId)
//                            .eq(EnterprisePerm::getTypeId, userId).one();
//                        //获取当前用户部门权限
//                        List<EnterprisePerm> deptPerms = enterprisePermMapper.lambdaQuery().eq(EnterprisePerm::getType, PermTypeEnum.DEPT.getPermTypeCode())
//                            .eq(EnterprisePerm::getTreeNodeId, treeNodeId)
//                            .in(CollectionUtils.isNotEmpty(deptIds) , EnterprisePerm::getTypeId, deptIds).list();
//                        //获取当前用户角色权限
//                        List<EnterprisePerm> rolePerms = enterprisePermMapper.lambdaQuery().eq(EnterprisePerm::getType, PermTypeEnum.ROLE.getPermTypeCode())
//                            .eq(EnterprisePerm::getTreeNodeId, treeNodeId)
//                            .in(roleIds!=null&&roleIds.size()>0,EnterprisePerm::getTypeId, roleIds).list();
//                        //获取当前职位职位权限
//                        EnterprisePerm jobPerm = enterprisePermMapper.lambdaQuery().eq(EnterprisePerm::getType, PermTypeEnum.JOB.getPermTypeCode())
//                            .eq(EnterprisePerm::getTreeNodeId, treeNodeId)
//                            .in(jobIds!=null&&jobIds.size()>0,EnterprisePerm::getTypeId, jobIds).one();

                        //筛选出部门的最高级
                        if (deptPerms != null && deptPerms.size() != 0) {
                            enterpriseDeptPerms.addAll(deptPerms);
                            deptPerm = enterpriseDeptPerms.iterator().next();
                        }
                        if (rolePerms != null && rolePerms.size() != 0) {
                            enterpriseDeptPerms.addAll(rolePerms);
                            rolePerm = enterpriseDeptPerms.iterator().next();
                        }
                        if (userPerm != null)
                            enterprisePerms.add(userPerm);
                        if (deptPerm != null )
                            enterprisePerms.add(deptPerm);
                        if (rolePerm != null )
                            enterprisePerms.add(rolePerm);
                        if (jobPerm != null )
                            enterprisePerms.add(jobPerm);

                        if (enterprisePerms.size() != 0){
                            topPerm = enterprisePerms.iterator().next();
                        }
                        return topPerm == null ? null : topPerm.getParams();
                    }
//                }
            } else {
                if (isCreator(userId, treeNodeId))return EnterprisePermTypeEnum.MANAGE.getPermTypeCode();
                else {
                    PriorityQueue<EnterprisePerm> enterprisePerms = new PriorityQueue<>();
                    PriorityQueue<EnterprisePerm> enterpriseDeptPerms = new PriorityQueue<>();
                    PriorityQueue<EnterprisePerm> enterpriseRolePerms = new PriorityQueue<>();

                    //获取当前用户权限
                    EnterprisePerm userPerm = enterprisePermMapper.selectOne(new LambdaQueryWrapper<EnterprisePerm>().eq(EnterprisePerm::getType, PermTypeEnum.USER.getPermTypeCode())
                        .eq(EnterprisePerm::getTreeNodeId, treeNodeId)
                        .eq(EnterprisePerm::getTypeId, userId));

                    //获取当前用户部门权限
                    List<EnterprisePerm> deptPerms = enterprisePermMapper.selectList(new LambdaQueryWrapper<EnterprisePerm>().eq(EnterprisePerm::getType, PermTypeEnum.DEPT.getPermTypeCode())
                        .eq(EnterprisePerm::getTreeNodeId, treeNodeId)
                        .in(CollectionUtils.isNotEmpty(deptIds), EnterprisePerm::getTypeId, deptIds));

                    //获取当前用户角色权限
                    List<EnterprisePerm> rolePerms = null;
                    if (roleIds!=null&&roleIds.size()>0) {
                        rolePerms = enterprisePermMapper.selectList(new LambdaQueryWrapper<EnterprisePerm>().eq(EnterprisePerm::getType, PermTypeEnum.ROLE.getPermTypeCode())
                            .eq(EnterprisePerm::getTreeNodeId, treeNodeId)
                            .in(roleIds != null && roleIds.size() > 0, EnterprisePerm::getTypeId, roleIds));
                    }

                    //获取当前职位职位权限
                    EnterprisePerm jobPerm = null;
                    if (jobIds!=null&&jobIds.size()>0) {
                        jobPerm = enterprisePermMapper.selectOne(new LambdaQueryWrapper<EnterprisePerm>().eq(EnterprisePerm::getType, PermTypeEnum.JOB.getPermTypeCode())
                            .eq(EnterprisePerm::getTreeNodeId, treeNodeId)
                            .in(jobIds != null && jobIds.size() > 0, EnterprisePerm::getTypeId, jobIds));
                    }



//                    //获取当前用户权限
//                    EnterprisePerm userPerm = enterprisePermMapper.lambdaQuery().eq(EnterprisePerm::getType, PermTypeEnum.USER.getPermTypeCode())
//                        .eq(EnterprisePerm::getTreeNodeId, treeNodeId)
//                        .eq(EnterprisePerm::getTypeId, userId).one();
//                    //获取当前用户部门权限
//                    List<EnterprisePerm> deptPerms = enterprisePermMapper.lambdaQuery().eq(EnterprisePerm::getType, PermTypeEnum.DEPT.getPermTypeCode())
//                        .eq(EnterprisePerm::getTreeNodeId, treeNodeId)
//                        .in(CollectionUtils.isNotEmpty(deptIds) , EnterprisePerm::getTypeId, deptIds).list();
//                    //获取当前用户角色权限
//                    List<EnterprisePerm> rolePerms = null;
//                    if (roleIds!=null&&roleIds.size()>0) {
//                        rolePerms = enterprisePermMapper.lambdaQuery().eq(EnterprisePerm::getType, PermTypeEnum.ROLE.getPermTypeCode())
//                            .eq(EnterprisePerm::getTreeNodeId, treeNodeId)
//                            .in(roleIds != null && roleIds.size() > 0, EnterprisePerm::getTypeId, roleIds).list();
//                    }
//                    //获取当前职位职位权限
//                    EnterprisePerm jobPerm = null;
//                    if (jobIds!=null&&jobIds.size()>0) {
//                        jobPerm = enterprisePermMapper.lambdaQuery().eq(EnterprisePerm::getType, PermTypeEnum.JOB.getPermTypeCode())
//                            .eq(EnterprisePerm::getTreeNodeId, treeNodeId)
//                            .in(jobIds != null && jobIds.size() > 0, EnterprisePerm::getTypeId, jobIds).one();
//
//                    }


                    //筛选出部门的最高级
                    if (deptPerms != null && deptPerms.size() != 0) {
                        enterpriseDeptPerms.addAll(deptPerms);
                        deptPerm = enterpriseDeptPerms.iterator().next();
                    }
                    if (rolePerms != null && rolePerms.size() != 0) {
                        enterpriseRolePerms.addAll(rolePerms);
                        rolePerm = enterpriseRolePerms.iterator().next();
                    }

                    if (userPerm != null)
                        enterprisePerms.add(userPerm);
                    if (deptPerm != null )
                        enterprisePerms.add(deptPerm);
                    if (rolePerm != null )
                        enterprisePerms.add(rolePerm);
                    if (jobPerm != null )
                        enterprisePerms.add(jobPerm);

                    if (enterprisePerms.size() != 0){
                        topPerm = enterprisePerms.iterator().next();
                    }
                    return topPerm == null ? null : topPerm.getParams();
                }
            }
        }
    }



    @Override
    public boolean isAdmin(Long userId){
        LoginUser userInfo = null;
        if (userId != null) {
            userInfo = sysUserService.getUserInfo(userId);
        } else {
            userInfo = LoginHelper.getLoginUser();
        }

        List<RemoteRoleVo> sysRoleVos = sysRoleService.selectUserRoleByUserId(userInfo.getUserId());
        for (RemoteRoleVo sysRoleVo : sysRoleVos) {
            if (sysRoleVo.getRoleId() == 1)
                return true;
        }
        return false;


//        FileUserDto userInfo = null;
//        if (userId!=null){
//            userInfo = FileUserUtils.getUserInfo(userId.toString());
//
//        }else {
//            userInfo = FileUserUtils.getUser();
//        }
//        Set<RoleSmallDto> roles = userInfo.getRoles();
//        for (RoleSmallDto role : roles) {
//            if (role.getId() == 1)
//                return true;
//        }
//        return false;
/*        if (userId==null){
            Set<RoleSmallDto> roles = FileUserUtils.getRoles();
            return FileUserUtils.getUser().getIsAdmin();
        }else {
            return FileUserUtils.getUserInfo(userId.toString()).getIsAdmin();
        }*/
    }


    @Override
    public boolean isEnterpriseAdmin(Long userId){
        LoginUser userInfo = null;
        if (userId != null) {
            userInfo = sysUserService.getUserInfo(userId);
        } else {
            userInfo = LoginHelper.getLoginUser();
        }
        List<RemoteRoleVo> sysRoleVos = sysRoleService.selectUserRoleByUserId(userInfo.getUserId());
        for (RemoteRoleVo sysRoleVo : sysRoleVos) {
            if (sysRoleVo.getRoleName().equals("企业文档管理员"))
                return true;
        }
        return false;
//        FileUserDto userInfo = null;
//        if (userId!=null){
//            userInfo = FileUserUtils.getUserInfo(userId.toString());
//
//        }else {
//            userInfo = FileUserUtils.getUser();
//        }
//        Set<RoleSmallDto> roles = userInfo.getRoles();
//        for (RoleSmallDto role : roles) {
//            if (role.getId() == 5)
//                return true;
//        }
//        return false;
    }


    /**
     * 新增第一级文件夹或者文件权限(管理员才能)
     * @return
     */
    @Override
    public void insertOneFolderPerm(Long treeNodeId, Long parentTreeNodeId, Long userId, EnterprisePermTypeEnum enterprisePermTypeEnum){
        EnterprisePermDto enterprisePermDto = new EnterprisePermDto();
        enterprisePermDto.setParentTreeNodeId(parentTreeNodeId).setTreeNodeId(treeNodeId).setType(PermTypeEnum.USER.getPermTypeCode()).setTypeId(userId).setPermCodes(enterprisePermTypeEnum.getPermTypeCode());
        insert(enterprisePermDto);
    }

    @Override
    public boolean isEnterpriseAdminOrAdmin(Long userId) {
        if (userId == null){
            return isAdmin(null )||isEnterpriseAdmin(null);
        }
        return isAdmin(userId )||isEnterpriseAdmin(userId);
    }


    /**
     * 查询当前用户是否为创建者
     * @param userId
     * @param treeNodeId
     * @return
     */
    public boolean isCreator(Long userId,Long treeNodeId){
        Long creatorId = null;
        if (userId ==null){
            creatorId = LoginHelper.getUserId();

        }else {
            creatorId = userId;
        }
        EnterpriseFilesTree enterpriseFilesTree = enterpriseFilesTreeMapper.selectById(treeNodeId);
//        EnterpriseFilesTree enterpriseFilesTree = enterpriseFilesTreeMapper.selectById(treeNodeId);
        String createId = enterpriseFilesTree.getCreateId();
        return creatorId.toString().equals(createId);
    }

    @Override
    public TableDataInfo<EnterpriseMemberVo> selectPermissionsByTreeNodeIdNew(@NotNull Long treeNodeId, String types, String params, String permName, Pageable pageable) {
        IPage<EnterprisePermVo> queryPage = PageUtil.toMybatisPage(pageable);
        List<String> typesArray = JSONArray.parseArray(types, String.class);
        List<String> paramsArray = JSONArray.parseArray(params, String.class);
        if (typesArray==null||typesArray.size()==0)typesArray =null;
        if (paramsArray==null||paramsArray.size()==0)paramsArray =null;
        if (permName==null||StringUtils.isNullOrBlank(permName))permName=null;
        IPage page = enterprisePermMapper.selectEnterpriseMemberVoNew(treeNodeId, permName, paramsArray, typesArray,queryPage);
        return TableDataInfo.build(page);

    }

    @Override
    public List<EnterpriseMemberVo> selectPermissionsByTreeNodeIdNew(@NotNull Long treeNodeId, String types, String params, String permName) {
        List<String> typesArray = JSONArray.parseArray(types, String.class);
        List<String> paramsArray = JSONArray.parseArray(params, String.class);
        if (typesArray==null||typesArray.size()==0)typesArray =null;
        if (paramsArray==null||paramsArray.size()==0)paramsArray =null;
        if (permName==null||StringUtils.isNullOrBlank(permName))permName=null;
        List info = enterprisePermMapper.selectEnterpriseMemberVoNew(treeNodeId, permName, paramsArray, typesArray);
        return info;

    }

    /**
     * 更新nodeId下的权限人员
     */
    @Override
    public void updatePermissionsByTreeNodeId(@NotNull List<Long> ids, @NotNull String params, @NotNull Long treeNodeId) {
        if (ids == null || ids.size() == 0){
            throw new RuntimeException("传递ids为空");
        }
        //检查权限
/*
        Boolean aBoolean = checkPermission(treeNodeId, EnterprisePermTypeEnum.MANAGE,null);
        if (!aBoolean) throw new RuntimeException("没有权限");
*/
        for (Long id : ids) {
            if (id == null|| StringUtils.isNullOrBlank(params)) throw new RuntimeException("必要参数存在为空");
            EnterprisePerm enterprisePerm = baseMapper.selectById(id);
            //禁止同级管同级
            if (enterprisePerm.getManage() == 1)//return;
                if (!isAdmin(null)) //continue;
                    throw new RuntimeException("同级权限不能管理同级权限");


            //禁止同级管同级
/*
            if (getPerms(treeNodeId,null).equals(EnterprisePermTypeEnum.MANAGE.getPermTypeCode())){
                if (!isAdmin(null)) //continue;
                    throw new BadRequestException("同级权限不能管理同级权限");
            }
*/

            EnterprisePermDto convert = MapstructUtils.convert(enterprisePerm, EnterprisePermDto.class);
            convert.setPermCodes(params);
            //修改本级
            updateById(MapstructUtils.convert(convert, EnterprisePerm.class));
            //修改下级
            updateChildrenAllPerm(treeNodeId,enterprisePerm.getTypeId(),PermTypeEnum.getPermTypeEnum(Integer.valueOf(enterprisePerm.getType())), EnterprisePermTypeEnum.getPermTypeEnum(params));
        }

        //查询当前文件的权限
//        List<EnterprisePerm> list = enterprisePermMapper.lambdaQuery().eq(EnterprisePerm::getTreeNodeId, treeNodeId).list();
//        List<SysLogPerm> collect = list.stream().map(res -> new SysLogPerm(String.valueOf(res.getTypeId()), res.getParams(),null)).collect(Collectors.toList());
//        sysDocLogService.createPermLog(String.valueOf(),null, TreeEnum.ENTERPRISE,
//                OperationEnum.UPDATE.getOperation(OperationEnum.OperationTypeEnum.JURISDICTION),enterpriseFilesTree.getRealName(),
//                enterpriseFilesTree.getPath(),enterpriseFilesTree.getDeleteType(),collect);

    }

    /**
     * 更新下级权限权限(不包含本级)
     */
    @Override
    public void updateChildrenAllPerm(Long treeNodeId, Long typeId, PermTypeEnum permTypeEnum, EnterprisePermTypeEnum enterprisePermTypeEnum){
        List<EnterpriseFilesTree> list = enterpriseFilesTreeMapper.lambdaQuery().isNull(EnterpriseFilesTree::getDeleteId).eq(EnterpriseFilesTree::getParentId, treeNodeId).list();
        for (EnterpriseFilesTree enterpriseFilesTree : list) {

            EnterprisePerm one = enterprisePermMapper.lambdaQuery().eq(EnterprisePerm::getTreeNodeId, enterpriseFilesTree.getId()).eq(EnterprisePerm::getType, permTypeEnum.getPermTypeCode()).eq(EnterprisePerm::getTypeId, typeId).one();
            if (one == null)continue;
            if (enterpriseFilesTree.getId()!=1&&enterpriseFilesTree.getType().equals(FileTypeEnum.FOLDER.getCode())&&(one.getIsExtend()==null||one.getIsExtend()==1)){
                EnterprisePermDto convert = MapstructUtils.convert(one, EnterprisePermDto.class);
                convert.setPermCodes(enterprisePermTypeEnum.getPermTypeCode());
                updateById(MapstructUtils.convert(convert, EnterprisePerm.class));

                updateChildrenAllPerm(enterpriseFilesTree.getId(), typeId,permTypeEnum,enterprisePermTypeEnum);
            }else if(enterpriseFilesTree.getType().equals(FileTypeEnum.FILE.getCode())&&(one.getIsExtend()==null||one.getIsExtend()==1)){
                EnterprisePermDto convert = MapstructUtils.convert(one, EnterprisePermDto.class);
                convert.setPermCodes(enterprisePermTypeEnum.getPermTypeCode());
                updateById(MapstructUtils.convert(convert, EnterprisePerm.class));
            }else {
                return;
            }
        }
    }

    /**
     * 本级权限新增
     * @param permTypeEnum
     * @param typeId
     * @param treeNodeId
     * @param parentId
     * @param enterprisePermTypeEnum
     */
    public void permInsert(PermTypeEnum permTypeEnum,Long typeId,Long treeNodeId,Long parentId,EnterprisePermTypeEnum enterprisePermTypeEnum){
        List<EnterprisePerm> list = enterprisePermMapper.lambdaQuery().eq(EnterprisePerm::getTypeId, typeId).eq(EnterprisePerm::getTreeNodeId, treeNodeId).eq(EnterprisePerm::getType,permTypeEnum.getPermTypeCode()).list();
        if (list.size()>1){
            enterprisePermMapper.lambdaUpdate().eq(EnterprisePerm::getType,permTypeEnum.getPermTypeCode()).eq(EnterprisePerm::getTypeId, typeId).eq(EnterprisePerm::getTreeNodeId, treeNodeId).remove();
        }else if(list.size()==1) {
            EnterprisePerm enterprisePerm = list.get(0);
            EnterprisePermDto enterprisePermDto1 = new EnterprisePermDto();
            enterprisePermDto1.setId(enterprisePerm.getId());
            enterprisePermDto1.setTreeNodeId(treeNodeId);
            enterprisePermDto1.setTypeId(typeId);
            enterprisePermDto1.setParentTreeNodeId(parentId);
            enterprisePermDto1.setType(permTypeEnum.getPermTypeCode());
            enterprisePermDto1.setPermCodes(enterprisePermTypeEnum.getPermTypeCode());
            enterprisePermDto1.setIsExtend(0);
            updateById(MapstructUtils.convert(enterprisePermDto1,EnterprisePerm.class));
        }
        EnterprisePermDto enterprisePermDto1 = new EnterprisePermDto();
        enterprisePermDto1.setTreeNodeId(treeNodeId);
        enterprisePermDto1.setTypeId(typeId);
        enterprisePermDto1.setParentTreeNodeId(parentId);
        enterprisePermDto1.setType(permTypeEnum.getPermTypeCode());
        enterprisePermDto1.setPermCodes(enterprisePermTypeEnum.getPermTypeCode());
        enterprisePermDto1.setIsExtend(0);
        insert(enterprisePermDto1);
    }
    /**
     * 检查当前用户在文件夹下是否有新增权限成员的权限
     * @param treeNodeId
     * @return
     */
    public Boolean checkPermissionsConfig(Long treeNodeId){
        //检查权限ee
        EnterpriseFilesTree enterpriseFilesTree = enterpriseFilesTreeMapper.selectById(treeNodeId);
        String perm = enterpriseFilesTree.getInsertPerm();
        EnterprisePermTypeEnum permTypeEnum = EnterprisePermTypeEnum.getPermTypeEnum(perm);
        if (permTypeEnum == EnterprisePermTypeEnum.NO)permTypeEnum = EnterprisePermTypeEnum.MANAGE;

        //当前文件夹的权限
        String perms = getPerms(treeNodeId,null);
        EnterprisePermTypeEnum ownPerm = EnterprisePermTypeEnum.getPermTypeEnum(perms);
        if (perms == null || ownPerm==EnterprisePermTypeEnum.NO)return false;
        else {
            return ownPerm.getPermRank() <= permTypeEnum.getPermRank();
        }

    }

    /**
     * 新增权限所有父级文件夹权限(不包含本级)
     * @param treeNodeId
     */
    public void insertLeaderFolderPerm(Long treeNodeId,PermTypeEnum permTypeEnum,Long userId,EnterprisePermTypeEnum enterprisePermTypeEnum){
        //新增权限的所有父级
        List<EnterpriseFilesTree> filesTrees = enterpriseFilesTreeMapper.selectSuperiorAll(treeNodeId.toString());
        for (EnterpriseFilesTree filesTree : filesTrees) {
            List<EnterprisePerm> list = enterprisePermMapper.lambdaQuery().eq(EnterprisePerm::getTreeNodeId, filesTree.getId()).eq(EnterprisePerm::getType, permTypeEnum.getPermTypeCode()).eq(EnterprisePerm::getTypeId, userId).list();
            if (list.size()==0){
                if (filesTree.getId()!=1&&filesTree.getId().longValue()!=treeNodeId.longValue()){
                    EnterprisePermDto enterprisePermDto1 = new EnterprisePermDto();
                    enterprisePermDto1.setTreeNodeId(filesTree.getId());
                    enterprisePermDto1.setTypeId(userId);
                    enterprisePermDto1.setParentTreeNodeId(Long.valueOf(filesTree.getParentId()));
                    enterprisePermDto1.setType(permTypeEnum.getPermTypeCode());
                    enterprisePermDto1.setPermCodes(enterprisePermTypeEnum.getPermTypeCode());
                    insert(enterprisePermDto1);
                }
            }
        }
    }

    /**
     * 新增权限所有子级文件和文件夹权限()
     * @param treeNodeId
     */
    public void insertChildrenAllPerm(Long treeNodeId,Long typeId,PermTypeEnum permTypeEnum,EnterprisePermTypeEnum enterprisePerm) {
        List<EnterpriseFilesTree> list = enterpriseFilesTreeMapper.lambdaQuery().isNull(EnterpriseFilesTree::getDeleteId).eq(EnterpriseFilesTree::getParentId, treeNodeId).list();
        for (EnterpriseFilesTree enterpriseFilesTree : list) {
            EnterprisePermDto enterprisePermDto1 = new EnterprisePermDto();
            enterprisePermDto1.setTreeNodeId(enterpriseFilesTree.getId());
            enterprisePermDto1.setTypeId(typeId);
            enterprisePermDto1.setIsExtend(1);
            enterprisePermDto1.setParentTreeNodeId(Long.valueOf(enterpriseFilesTree.getParentId()));
            enterprisePermDto1.setType(permTypeEnum.getPermTypeCode());
            enterprisePermDto1.setPermCodes(enterprisePerm.getPermTypeCode());
            EnterprisePerm one = enterprisePermMapper.lambdaQuery().eq(EnterprisePerm::getType, permTypeEnum.getPermTypeCode()).eq(EnterprisePerm::getTypeId, typeId).eq(EnterprisePerm::getTreeNodeId, enterpriseFilesTree.getId()).one();
            //下级文件夹存在权限
            if (one!=null){
                removeById(one.getId());
            }
            if (enterpriseFilesTree.getType().equals(FileTypeEnum.FOLDER.getCode())){
                insert(enterprisePermDto1);
                insertChildrenAllPerm(enterpriseFilesTree.getId(), typeId,permTypeEnum,enterprisePerm);
            }else if(enterpriseFilesTree.getType().equals(FileTypeEnum.FILE.getCode())||enterpriseFilesTree.getType().equals(FileTypeEnum.RICH_TEXT.getCode())){
                insert(enterprisePermDto1);
            }else {
                return;
            }
        }
    }

    /**
     * 删除权限所有父级文件夹权限
     * @param treeNodeId
     */
    public void deleteLeaderFolderPerm(Long treeNodeId,PermTypeEnum permTypeEnum,Long typeId){
        //新增权限的所有父级
        List<EnterpriseFilesTree> filesTrees = enterpriseFilesTreeMapper.selectSuperiorAll(treeNodeId.toString());
        Collections.reverse(filesTrees);
        //去掉本级节点
        filesTrees.remove(0);


        for (EnterpriseFilesTree filesTree : filesTrees) {
            if (filesTree.getId() !=1){
                EnterprisePerm one = enterprisePermMapper.lambdaQuery().eq(EnterprisePerm::getTreeNodeId, filesTree.getId()).eq(EnterprisePerm::getType, permTypeEnum.getPermTypeCode()).eq(EnterprisePerm::getTypeId, typeId).one();
                if (one!=null){
                    if (filesTree.getId().longValue()!=treeNodeId.longValue()&&(one.getIsExtend()==null||one.getIsExtend() == 1)){
                        removeById(one.getId());
                    } else if (filesTree.getId().longValue()!=treeNodeId.longValue()&&one.getIsExtend() != 1){
                        break;
                    }
                }
            }
        }
    }

    /**
     * 删除权限所有子级文件和文件夹权限
     * @param treeNodeId
     */
    public void deleteChildrenAllPerm(Long treeNodeId,PermTypeEnum permTypeEnum,Long typeId) {
        List<EnterpriseFilesTree> list = enterpriseFilesTreeMapper.lambdaQuery().isNull(EnterpriseFilesTree::getDeleteId).eq(EnterpriseFilesTree::getParentId, treeNodeId).list();
        for (EnterpriseFilesTree enterpriseFilesTree : list) {
            EnterprisePerm one = baseMapper.lambdaQuery().eq(EnterprisePerm::getTreeNodeId, enterpriseFilesTree.getId()).eq(EnterprisePerm::getType, permTypeEnum.getPermTypeCode()).eq(EnterprisePerm::getTypeId, typeId).one();
            if (one!=null){
                if (enterpriseFilesTree.getId()!=1&&enterpriseFilesTree.getType().equals(FileTypeEnum.FOLDER.getCode())&&(one.getIsExtend()==null||one.getIsExtend()==1)){
                    removeById(one.getId());
                    deleteChildrenAllPerm(enterpriseFilesTree.getId(),permTypeEnum, typeId);
                }else if((enterpriseFilesTree.getType().equals(FileTypeEnum.FILE.getCode())||enterpriseFilesTree.getType().equals(FileTypeEnum.RICH_TEXT.getCode()))&&(one.getIsExtend()==null||one.getIsExtend()==1)){
                    removeById(one.getId());
                }else {
                    return;
                }
            }
        }
        return;
    }



    /**
     * 数组形式新增权限()
     * @param enterprisePermDtos
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertPermissionsByTreeNodeIds(@NotNull List<EnterprisePermDto> enterprisePermDtos, @NotNull Long treeNodeId){
        //检查是否有新增权限成员的权限
/*
        Boolean aBoolean = checkPermissionsConfig(treeNodeId);
        if (!aBoolean)throw new RuntimeException("没有权限新增成员");
*/
        //检查新增权限是否超过自身的权限
        LoginUser loginUser = LoginHelper.getLoginUser();
        String perms = getPerms(treeNodeId, loginUser.getUserId());
/*
        EnterprisePermTypeEnum permTypeEnum = EnterprisePermTypeEnum.getPermTypeEnum(perms);
        if (permTypeEnum == EnterprisePermTypeEnum.NO)throw new RuntimeException("你在此文件夹没有权限");
*/
        Map<Integer, List<EnterprisePermDto>> collect = enterprisePermDtos.stream().collect(Collectors.groupingBy(EnterprisePermDto::getType));
        List<EnterprisePermDto> userPerms = collect.get(PermTypeEnum.USER.getPermTypeCode());
        List<EnterprisePermDto> deptPerms = collect.get(PermTypeEnum.DEPT.getPermTypeCode());
        List<EnterprisePermDto> jobPerms = collect.get(PermTypeEnum.JOB.getPermTypeCode());
        List<EnterprisePermDto> rolePerms = collect.get(PermTypeEnum.ROLE.getPermTypeCode());

        EnterpriseFilesTree enterpriseFilesTree = enterpriseFilesTreeMapper.selectById(treeNodeId);
        String parentId = enterpriseFilesTree.getParentId();
        if (userPerms!=null)
            for (EnterprisePermDto enterprisePermDto : userPerms) {
                //本级
                permInsert(PermTypeEnum.USER, enterprisePermDto.getTypeId(),treeNodeId, Long.valueOf(parentId),EnterprisePermTypeEnum.getPermTypeEnum(enterprisePermDto.getPermCodes()));
                //新增父级文件夹权限
                insertLeaderFolderPerm(treeNodeId,PermTypeEnum.USER,enterprisePermDto.getTypeId(),EnterprisePermTypeEnum.QUERY);
                //子级
                insertChildrenAllPerm(treeNodeId,enterprisePermDto.getTypeId(),PermTypeEnum.USER,EnterprisePermTypeEnum.getPermTypeEnum(enterprisePermDto.getPermCodes()));
            }
        if (deptPerms!=null)
            for (EnterprisePermDto enterprisePermDto : deptPerms) {
                permInsert(PermTypeEnum.DEPT, enterprisePermDto.getTypeId(),treeNodeId, Long.valueOf(parentId),EnterprisePermTypeEnum.getPermTypeEnum(enterprisePermDto.getPermCodes()));
                //新增父级文件夹权限
                insertLeaderFolderPerm(treeNodeId,PermTypeEnum.DEPT,enterprisePermDto.getTypeId(),EnterprisePermTypeEnum.QUERY);
                insertChildrenAllPerm(treeNodeId,enterprisePermDto.getTypeId(),PermTypeEnum.DEPT,EnterprisePermTypeEnum.getPermTypeEnum(enterprisePermDto.getPermCodes()));
            }
        if (jobPerms!=null)
            for (EnterprisePermDto enterprisePermDto : jobPerms) {
                permInsert(PermTypeEnum.JOB, enterprisePermDto.getTypeId(),treeNodeId, Long.valueOf(parentId),EnterprisePermTypeEnum.getPermTypeEnum(enterprisePermDto.getPermCodes()));
                //新增父级文件夹权限
                insertLeaderFolderPerm(treeNodeId,PermTypeEnum.JOB,enterprisePermDto.getTypeId(),EnterprisePermTypeEnum.QUERY);
                insertChildrenAllPerm(treeNodeId,enterprisePermDto.getTypeId(),PermTypeEnum.JOB,EnterprisePermTypeEnum.getPermTypeEnum(enterprisePermDto.getPermCodes()));
            }
        if (rolePerms!=null)
            for (EnterprisePermDto enterprisePermDto : rolePerms) {
                permInsert(PermTypeEnum.ROLE, enterprisePermDto.getTypeId(),treeNodeId, Long.valueOf(parentId),EnterprisePermTypeEnum.getPermTypeEnum(enterprisePermDto.getPermCodes()));
                //新增父级文件夹权限
                insertLeaderFolderPerm(treeNodeId,PermTypeEnum.ROLE,enterprisePermDto.getTypeId(),EnterprisePermTypeEnum.QUERY);
                insertChildrenAllPerm(treeNodeId,enterprisePermDto.getTypeId(),PermTypeEnum.ROLE,EnterprisePermTypeEnum.getPermTypeEnum(enterprisePermDto.getPermCodes()));
            }
        //查询当前文件的权限
/*
        List<EnterprisePerm> list = enterprisePermMapper.lambdaQuery().eq(EnterprisePerm::getTreeNodeId, treeNodeId).list();
        List<SysLogPerm> collect2 = list.stream().map(res -> new SysLogPerm(res.getTypeId(),Integer.parseInt(res.getType()), res.getParams(),null)).collect(Collectors.toList());

        sysDocLogService.createPermLog(String.valueOf(treeNodeId),null, TreeEnum.ENTERPRISE,
            OperationEnum.INSERT.getOperation(OperationEnum.OperationTypeEnum.JURISDICTION),enterpriseFilesTree.getRealName(),
            enterpriseFilesTree.getPath(),enterpriseFilesTree.getDeleteType(),collect2);
*/
    }

    /**
     * 删除nodeId下的权限人员
     */

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deletePermissionsByTreeNodeId(@NotNull List<Long> ids, @NotNull Long treeNodeId) {
        if (ids == null || ids.size() == 0){
            throw new RuntimeException("传递ids为空");
        }
        LoginUser loginUser = LoginHelper.getLoginUser();
        Long userId = loginUser.getUserId();
        EnterpriseFilesTree enterpriseFilesTree = null;
/*
        Boolean aBoolean = checkPermission(treeNodeId, EnterprisePermTypeEnum.MANAGE,null);
        if (!aBoolean) throw new RuntimeException("没有权限");
*/
        for (Long id : ids) {
            EnterprisePerm enterprisePerm = baseMapper.selectById(id);
            Long typeId = enterprisePerm.getTypeId();
            //禁止删除自己
            if (userId.longValue() == typeId.longValue())//continue;
                throw new RuntimeException("不能删除自身的权限");

            //禁止同级管同级
            if (enterprisePerm.getManage() == 1) {
                if (!isAdmin(null)) //continue;
                    throw new RuntimeException("同级权限不能管理同级权限");
            }
            //禁止同级管同级
/*
            if (getPerms(treeNodeId,null).equals(EnterprisePermTypeEnum.MANAGE.getPermTypeCode())){
                if (!isAdmin(null)) //continue;
                    throw new BadRequestException("同级权限不能管理同级权限");
            }
*/
            baseMapper.deleteById(id);

            //删除上级文件夹权限
            deleteLeaderFolderPerm(enterprisePerm.getTreeNodeId(),PermTypeEnum.getPermTypeEnum(Integer.valueOf(enterprisePerm.getType())),enterprisePerm.getTypeId());
            //删除子级所有文件权限
            deleteChildrenAllPerm(enterprisePerm.getTreeNodeId(),PermTypeEnum.getPermTypeEnum(Integer.valueOf(enterprisePerm.getType())),enterprisePerm.getTypeId());
        }

        //检查权限
//        enterpriseFilesTree = enterpriseFilesTreeMapper.selectById(treeNodeId);
//        if (enterpriseFilesTree!=null && treeNodeId!=null) {
//            //查询当前文件的权限
//            List<EnterprisePerm> list = enterprisePermMapper.lambdaQuery().eq(EnterprisePerm::getTreeNodeId, treeNodeId).list();
//            List<SysLogPerm> collect = list.stream().map(res -> new SysLogPerm(String.valueOf(res.getTypeId()), res.getParams(), null)).collect(Collectors.toList());
//            sysDocLogService.createPermLog(String.valueOf(permResource.getId()), null, TreeEnum.ENTERPRISE,
//                    OperationEnum.DELETE.getOperation(OperationEnum.OperationTypeEnum.JURISDICTION), enterpriseFilesTree.getRealName(),
//                    enterpriseFilesTree.getPath(), enterpriseFilesTree.getDeleteType(), collect);
//        }
    }

    /**
     * 同步下级权限权限
     */
    @Override
    public void synchronizedChildrenAllPerm(Long treeNodeId) throws InterruptedException {
        LoginUser loginUser = LoginHelper.getLoginUser();
        Boolean aBoolean = checkPermission(treeNodeId, EnterprisePermTypeEnum.MANAGE, loginUser.getUserId());
        if (!aBoolean){
            throw new RuntimeException("没有权限操作");
        }
/*
        MessageDto messageDto = new MessageDto();
        messageDto.setUserId(user.getId());
        messageDto.setTreeNodeId(treeNodeId);
        messageDto.setUserName(user.getUsername());
        rabbitMessageSender.send2Epu(JSONObject.toJSONString(messageDto));
*/

    }

    /**
     * 移交权限
     */

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void transferPerm(Long transferId, Long targetId) {
        if (transferId == null || targetId == null || transferId.longValue() == targetId.longValue())throw new IllegalArgumentException("参数错误");

        List<EnterprisePerm> transferPerms = enterprisePermMapper.lambdaQuery().eq(EnterprisePerm::getType, PermTypeEnum.USER.getPermTypeCode()).eq(EnterprisePerm::getTypeId, transferId).list();
        List<EnterprisePerm> targetPerms = enterprisePermMapper.lambdaQuery().eq(EnterprisePerm::getType, PermTypeEnum.USER.getPermTypeCode()).eq(EnterprisePerm::getTypeId, targetId).list();

        List<Long> targetSameIds = new ArrayList<>();
        ArrayList<Long> b = new ArrayList<>();

        List<EnterprisePerm> samePerms = transferPerms.stream().filter(transferPerm ->
            targetPerms.stream().anyMatch(targetPerm -> {
                if (targetPerm.getTreeNodeId().equals(transferPerm.getTreeNodeId())){
                    if ((EnterprisePermTypeEnum.getPermTypeEnum(transferPerm.getParams()).getPermRank() < EnterprisePermTypeEnum.getPermTypeEnum(targetPerm.getParams()).getPermRank())){
                        targetSameIds.add(targetPerm.getId());
                        return true;
                    } else {
                        b.add(transferPerm.getId());
                        return false;
                    }
                }else {
                    return false;
                }
            })
        ).collect(Collectors.toList());
        //找出差异()
        List<EnterprisePerm> diffPerms = transferPerms.stream().filter(transferPerm -> targetPerms.stream().noneMatch(targetPerm -> targetPerm.getTreeNodeId().equals(transferPerm.getTreeNodeId()))).collect(Collectors.toList());
        List<Long> sameIds = samePerms.stream().map(EnterprisePerm::getId).collect(Collectors.toList());
        List<Long> diffIds = diffPerms.stream().map(EnterprisePerm::getId).collect(Collectors.toList());

        if (b.size()>0){
            enterprisePermMapper.lambdaUpdate().in(EnterprisePerm::getId, b).remove();
        }
        if (targetSameIds.size()>0){
            enterprisePermMapper.lambdaUpdate().in(EnterprisePerm::getId, targetSameIds).remove();
        }
        if (sameIds.size()>0){
            enterprisePermMapper.lambdaUpdate().in(EnterprisePerm::getId, sameIds).set(EnterprisePerm::getTypeId, targetId).update();
        }
        if (diffIds.size()>0){
            enterprisePermMapper.lambdaUpdate().in( EnterprisePerm::getId, diffIds).set(EnterprisePerm::getTypeId, targetId).update();
        }

    }
}
